﻿#include "FCWorkFlow.h"
#include <QPointer>



class FCWorkFlowPrivate {
    FC_IMPL_PUBLIC(FCWorkFlow)
public:
    FCWorkFlowPrivate(FCWorkFlow *p);
    QHash<FCNodeMetaData, QPointer<FCAbstractNodeFactory> > _metaToFactory;///< 记录prototype对应的工厂
    QList<FCWorkFlow::FCAbstractNodeSmtPtr> _nodes;
};

FCWorkFlowPrivate::FCWorkFlowPrivate(FCWorkFlow *p) : q_ptr(p)
{
}


FCWorkFlow::FCWorkFlow(QObject *p) : QObject(p)
    , d_ptr(new FCWorkFlowPrivate(this))
{
}


FCWorkFlow::~FCWorkFlow()
{
}


/**
 * @brief 注册工厂，工作流不保留工程的内存管理权
 * @param factory
 */
void FCWorkFlow::registFactory(FCAbstractNodeFactory *factory)
{
    QList<FCNodeMetaData> mds = factory->getNodesMetaData();

    for (const FCNodeMetaData& m : mds)
    {
        d_ptr->_metaToFactory[m] = factory;
    }
}


/**
 * @brief 注册工厂群，工作流不保留工程的内存管理权
 * @param factory
 */
void FCWorkFlow::registFactorys(const QList<FCAbstractNodeFactory *> factorys)
{
    for (FCAbstractNodeFactory *f : factorys)
    {
        registFactory(f);
    }
}


/**
 * @brief 工作流创建节点，FCWorkFlow保留节点的内存管理权
 * @param md
 * @return
 */
FCWorkFlow::FCAbstractNodeSmtPtr FCWorkFlow::createNode(const FCNodeMetaData& md)
{
    QPointer<FCAbstractNodeFactory> pointer = d_ptr->_metaToFactory.value(md, nullptr);

    if (pointer.isNull()) {
        return (nullptr);
    }
    FCAbstractNodeSmtPtr node(pointer->create(md));

    d_ptr->_nodes.append(node);
    emit nodeCreated(node);

    return (node);
}
